#include "netcli.hpp"
#include <arpa/inet.h>
#include <cstring>
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

netcli::netcli(int port)
{
    int ret = 0;
    struct sockaddr_in local_addr;

    this->port = port;

    fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd < 0) {
        std::cerr << "Could not create socket" << std::endl;
        return;
    }

    memset(&local_addr, 0, sizeof(local_addr));
    local_addr.sin_family = AF_INET;
    local_addr.sin_addr.s_addr = INADDR_ANY;
    local_addr.sin_port = htons(port);
    ret = bind(fd, (struct sockaddr*)&local_addr, sizeof(local_addr));
    if (ret < 0) {
        std::cerr << "Could not bind socket" << std::endl;
        close(fd);
        return;
    }
}

netcli::~netcli()
{
    close(fd);
}

int netcli::recv(char* buf, int size)
{
    int ret = 0;
    socklen_t len = 0;
    struct sockaddr_in ser_addr;

    len = sizeof(struct sockaddr_in);
    ret = recvfrom(fd, (char*)buf, size, MSG_WAITALL, (struct sockaddr*)&ser_addr, &len);
    if (ret < 0) {
        std::cerr << "Receive failed" << std::endl;
        return 1;
    }
    buf[ret] = '\0';

    return 0;
}
